package com.zspringboot.demo.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zspringboot.demo.common.Constants;
import com.zspringboot.demo.common.Result;
import com.zspringboot.demo.controller.dto.UserDTO;
import com.zspringboot.demo.entity.User;
import com.zspringboot.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author laolang
 * @since 2024-02-18
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private IUserService userService;

    // 新增/修改
    @PostMapping
    public Result save(@RequestBody User user) {
            return Result.success(userService.saveOrUpdate(user));
            }
    // 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
            return Result.success(userService.removeById(id));
            }
    // 批量删除
    @PostMapping("/del/batch")
    public Result deleteBacth(@RequestBody List<Integer> ids){
        return Result.success(userService.removeByIds(ids));
        }
    // 查询所有数据
    @GetMapping
    public Result findAll() {
            return Result.success(userService.list());
            }

    // 根据id 查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
            return Result.success(userService.getById(id));
            }

    @GetMapping("/username/{username}")
    public Result Person(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper));
    }
    // 分页
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String username,
                               @RequestParam(defaultValue = "") String nickname,
                               @RequestParam(defaultValue = "") String email) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//            queryWrapper.orderByDesc("id");
        if (!"".equals(username))
            queryWrapper.like("username",username);
        if (!"".equals(nickname))
            queryWrapper.like("nickname",nickname);
        if (!"".equals(email))
            queryWrapper.like("email",email);// and
//        queryWrapper.or().like("address",address);   or
//        queryWrapper.orderByDesc("id");
            return Result.success(userService.page(new Page<>(pageNum, pageSize),queryWrapper));
            }

    /**
     * 导出
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List<User> list = userService.list();// 从数据库查出所有数据
        ExcelWriter writer = ExcelUtil.getWriter(true);// 在内存操作，写出到浏览器
        // 自定义标题别名
//        writer.addHeaderAlias("username","用户名");
//        writer.addHeaderAlias("password","密码");
//        writer.addHeaderAlias("nickname","昵称");
//        writer.addHeaderAlias("email","邮箱");
//        writer.addHeaderAlias("phone","电话");
//        writer.addHeaderAlias("address","地址");
//        writer.addHeaderAlias("createTime","创建时间");
//        writer.addHeaderAlias("avatarUrl","头像");

        // 一次性洗出 list 内的对象到 excel，使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器相应样式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<User> list = reader.readAll(User.class);
        System.out.println(list);
        userService.saveBatch(list);
        return true;
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO user) {
        String username = user.getUsername();
        String password = user.getPassword();
        if (StrUtil.isBlankIfStr(username)|| StrUtil.isBlankIfStr(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        return Result.success(userService.login(user));
    }
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlankIfStr(username)|| StrUtil.isBlankIfStr(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        return Result.success(userService.register(userDTO));
    }
    // 重置密码
    @PostMapping("/resetPassword{id}")
    public Result resetPassword(@PathVariable Integer id){
        Integer t = userService.resetPassword(id);
        if (t==1){
            return Result.success();
        }
        return Result.error(Constants.CODE_600,"修改失败");
    }


}

